import { NextRequest, NextResponse } from 'next/server'

// FastGPT服务器地址配置
const FASTGPT_BASE_URL = process.env.FASTGPT_BASE_URL || 'https://fastgpt2.vertu.cn/api/v1/chat/completions'
const FASTGPT_API_KEY = process.env.FASTGPT_API_KEY || 'fastgpt-jtu0gvLwjdc9DRnDvIUZ8SakESKkvG9rkplB0MsarrYMOubtMCU5e'

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()

    console.log('🚀 转发聊天请求到FastGPT:', {
      chatId: body.chatId,
      stream: body.stream,
      messageCount: body.messages?.length || 0
    })

    // 转发请求到FastGPT
    const response = await fetch(FASTGPT_BASE_URL, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${FASTGPT_API_KEY}`,
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream',
      },
      body: JSON.stringify(body)
    })

    if (!response.ok) {
      // 先读取错误响应体用于日志
      const errorBody = await response.text()
      console.error('❌ FastGPT API请求失败:', {
        status: response.status,
        statusText: response.statusText,
        body: errorBody
      })

      return NextResponse.json(
        { error: 'FastGPT API请求失败', details: errorBody },
        { status: response.status }
      )
    }

    // 检查是否是流式响应
    if (body.stream && response.headers.get('content-type')?.includes('text/event-stream')) {
      console.log('📡 返回流式响应')

      // 创建流式响应转发
      const reader = response.body?.getReader()
      const encoder = new TextEncoder()

      const stream = new ReadableStream({
        async start(controller) {
          try {
            while (true) {
              const { done, value } = await reader!.read()
              if (done) break

              // 转发数据块
              controller.enqueue(value)
            }
          } catch (error) {
            console.error('❌ 流式响应转发失败:', error)
          } finally {
            controller.close()
            reader?.releaseLock()
          }
        }
      })

      return new Response(stream, {
        headers: {
          'Content-Type': 'text/event-stream',
          'Cache-Control': 'no-cache',
          'Connection': 'keep-alive',
        },
      })
    }

    // 非流式响应，直接返回JSON
    console.log('📋 返回JSON响应')
    const data = await response.json()
    return NextResponse.json(data)

  } catch (error) {
    console.error('❌ 聊天API转发失败:', error)
    return NextResponse.json(
      { error: '内部服务器错误', message: error instanceof Error ? error.message : '未知错误' },
      { status: 500 }
    )
  }
}

// 支持预检请求
export async function OPTIONS() {
  return new NextResponse(null, {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    },
  })
}
